// BioCapture.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "biohelper.h"

//
// Flow macros
// 

static 
void
WINAPI
_OutputDbgStr(
    __in  LPSTR szFile,
    __in  DWORD dwLine,
    __in  LPSTR szMsg,
    __in  HRESULT hr)
{
    CHAR rgsz [256];
    LPSTR szTag = "INFO";

    if (FAILED(hr))
        szTag = "ERROR";

    StringCbPrintfA(
        rgsz,
        sizeof(rgsz),
        "%s: %s - 0x%x, file %s, line %d\n",
        szTag,
        szMsg,
        hr,
        szFile,
        dwLine);
    printf(rgsz);
}

#define CHECK_HR(_X) {                                          \
    if (FAILED(hr = _X)) {                                      \
        _OutputDbgStr(__FILE__, __LINE__, #_X, (DWORD) hr);     \
        __leave;                                                \
    }                                                           \
}

//
// Callback for when a fingerprint scan completes
//
void
WINAPI
_BioHelperCallback(
    __in            PBIO_HELPER_CONTEXT pCtx)
{
    if (TRUE == pCtx->fMatchesLoggedOnUser)
        printf("Success: scan matches logged on user.\n");
    else
        printf("Fail: scan didn't match logged on user.\n");
    SetEvent((HANDLE) pCtx->pvCallerCtx);
}

//
// Main test entry point
//
int _tmain(__in int argc, __in_ecount(argc) _TCHAR* argv[])
{
    HRESULT hr = S_OK;
    BIO_HELPER_CONTEXT BhCtx = {0};
    HANDLE hStopEvent = NULL;
    BOOL fInit = FALSE;
    
    UNREFERENCED_PARAMETER(argc);
    UNREFERENCED_PARAMETER(argv);

    __try
    {
        //
        // Initialize
        //

        CHECK_HR(BHInitialize(&BhCtx));
        fInit = TRUE;

        //
        // Attempt a fingerprint scan and match
        //

        if (NULL == (hStopEvent = CreateEvent(NULL, FALSE, FALSE, NULL)))
        {
            hr = (HRESULT) GetLastError();
            __leave;
        }

        BhCtx.pfnCallback = _BioHelperCallback;
        BhCtx.pvCallerCtx = hStopEvent;

        while (FALSE == BhCtx.fMatchesLoggedOnUser)
        {
            printf("Waiting for fingerprint scan ...\n");
            CHECK_HR(BHIdentifyAsync(&BhCtx));
    
            WaitForSingleObject(hStopEvent, INFINITE);
        }
    }
    __finally
    {
        if (NULL != hStopEvent)
            CloseHandle(hStopEvent);
        if (TRUE == fInit)
            BHCleanup(&BhCtx);
    }

    return (int) hr;
}

